import { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
import { fail } from "../utils/response";
import config from "../config";
import { JwtPayload } from "../types/index";

export const auth = async (req: Request, res: Response, next: NextFunction) => {
  try {
    console.log("Session ID:", req.sessionID);
    console.log("Session user:", req.session?.user);
    const token = req.headers.authorization?.split(" ")[1];
    if (!token) return fail(res, 401, "未登录");

    // @ts-ignore
    const decoded: JwtPayload = jwt.verify(token, config.jwt.secret);
    const session_user = req.session?.user;
    if (
      !session_user ||
      !session_user.userId ||
      session_user.userId !== decoded.userId
    ) {
      throw new Error("token 无效，请重新登录");
    }
    req.user = decoded;
    next();
  } catch (err) {
    console.log(err);
    return fail(res, 401, "token 无效");
  }
};

export const roleCheck = (roles: string[]) => {
  return (req: Request, res: Response, next: NextFunction) => {
    if (!req.user) return fail(res, 401, "未登录");
    if (!roles.includes(req.user.role)) {
      return fail(res, 403, "没有权限");
    }
    next();
  };
};
